<template>
  <view class="content">
    <uv-loading-page
      :loading="loading"
      loading-text="加载中..."
      font-size="24rpx"
    ></uv-loading-page>
    <view class="banner">
      <image
        src="https://wds-service-1258344699.file.myqcloud.com/20/17270/png/169441763076261c4ea51924e11f4957be7a84f48a08f.png?version=0"
        mode="widthFix"
      />
    </view>
    <view class="classification">
      <div class="cell" v-if="list.length">
        <div class="bold shrink fz14">{{ list[current.index1].title }}:</div>
        <div
          class="box fz12"
          :class="{ active: isSelectAll }"
          @click="toSelectAll"
        >
          全部
        </div>
        <view class="flex flexWrap">
          <div
            class="box fz12"
            v-for="(item, index) in list"
            :key="index"
            @click="setCurrent('index1', index)"
            :class="{ active: !isSelectAll && current.index1 == index }"
          >
            {{ item.name }}
          </div>
        </view>
      </div>

      <div
        class="cell"
        v-if="
          !isSelectAll && twoList && twoList.children && twoList.children.length
        "
      >
        <div class="bold shrink fz14">{{ twoList.children[0].title }}:</div>
        <view class="flex flexWrap">
          <div
            class="box fz12"
            v-for="(item, index) in twoList.children"
            :key="index"
            @click="setCurrent('index2', index)"
            :class="{ active: current.index2 === index }"
          >
            {{ item.name }}
          </div>
        </view>
      </div>

      <div
        class="cell"
        v-if="threeList && threeList.children && threeList.children.length"
      >
        <div class="bold shrink fz14">{{ threeList.children[0].title }}:</div>
        <view class="flex flexWrap">
          <div
            class="box fz12"
            v-for="(item, index) in threeList.children"
            :key="index"
            @click="setCurrent('index3', index)"
            :class="{ active: current.index3 == index }"
          >
            {{ item.name }}
          </div>
        </view>
      </div>

      <div
        class="cell"
        v-if="fourList && fourList.children && fourList.children.length"
      >
        <div class="bold shrink fz14">{{ fourList.children[0].title }}:</div>
        <view class="flex flexWrap">
          <div
            class="box fz12"
            v-for="(item, index) in fourList.children"
            :key="index"
            @click="setCurrent('index4', index)"
            :class="{ active: current.index4 === index }"
          >
            {{ item.name }}
          </div>
        </view>
      </div>

      <div
        class="courses flex justifyCenter alignCenter"
        v-if="!isSelectAll && !courseList.length"
      >
        <uv-empty mode="data" text="暂无相关课程"></uv-empty>
      </div>

      <div class="courses grids gridColumns2">
        <div
          class="box"
          v-for="(item, index) in isSelectAll ? originalCourseList : courseList"
          :key="index"
          @click="
            proxy.$utils.toLink(
              `/packagePages/curriculum/details?id=${item._id}`
            )
          "
        >
          <div class="img">
            <image :src="item.coverUrl[0]" mode="widthFix" />
          </div>
          <div class="info">
            <div
              class="twoPrice flex alignCenter"
              v-if="counter.priceRange(item.lessonContent)"
            >
              <div class="newPrice fz16 bold">
                <span>¥</span>{{ counter.priceRange(item.lessonContent) }}
              </div>
              <div class="oldPrice fz14"><span>¥</span>{{ item.price }}</div>
            </div>
            <div class="price fz16 bold" v-else>
              <span>¥</span>{{ item.price }}
            </div>
            <div class="desc fz12">{{ item.name }}</div>
            <div class="time fz12" v-if="item.courseDuration">
              总计课时:{{ item.courseDuration }}
            </div>
          </div>
          <div class="btn fz14">课程详情</div>
        </div>
      </div>
    </view>
  </view>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
import useCounterStore from "@/stores/counter";
const counter = useCounterStore();
const instance = getCurrentInstance();

//data
let list = ref([]);
let current = ref({});
let courseList = ref([]); //课程中心
let loading = ref(false);
let isSelectAll = ref(true);

let twoList = computed(() => {
  if (!list.value.length) return;
  return list.value[current.value.index1];
});

let threeList = computed(() => {
  if (twoList.value && twoList.value.children && twoList.value.children.length)
    return twoList.value.children[current.value.index2];
});

let fourList = computed(() => {
  if (
    threeList.value &&
    threeList.value.children &&
    threeList.value.children.length
  )
    return threeList.value.children[current.value.index3];
});

let originalCourseList = computed(() => {
  return counter.ycMpParams.courseList;
});

onShow(() => {
  getInfo();
});

function handleLoad() {
  loading.value = false;
}

function toSelectAll() {
  isSelectAll.value = true;
  current.value.index2 = null;
  current.value.index3 = null;
  current.value.index4 = null;
}

async function getInfo() {
  try {
    loading.value = true;
    let arr = [];
    let resp = await proxy.$apis.getCurriculum();
    let news = proxy.$utils.transformArray(resp, "_id", "parentId");
    news.forEach((element) => {
      if (element.hasOwnProperty("pageShow") && element.pageShow == 0) {
      } else {
        arr.push(element);
      }
    });
    // console.log("处理后的分类", arr);
    list.value = proxy.$utils.deepcopy(arr);
    const depth = calculateDepth(list.value, "children");
    for (let index = 0; index < depth; index++) {
      current.value[`index${index + 1}`] = 0;
    }
    await getList();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function setDefault() {
  console.log("tab2Params", counter.tab2Params);
  if (!counter.tab2Params.length) return;
  console.log("tab2Params333", counter.tab2Params);
  console.log("全部分类", list.value);
  let type = [...counter.tab2Params];
  current.value = {};
  if (type.length >= 1) {
    let index1 = proxy.$utils.findIndexByField(list.value, "_id", type[0]);
    current.value.index1 = index1;
    isSelectAll.value = false;
  }
  if (type.length >= 2) {
    let index2 = proxy.$utils.findIndexByField(
      twoList.value.children,
      "_id",
      type[1]
    );
    current.value.index2 = index2;
  }

  if (type.length >= 3) {
    let index3 = proxy.$utils.findIndexByField(
      threeList.value.children,
      "_id",
      type[2]
    );
    current.value.index3 = index3;
  }

  if (type.length >= 4) {
    let index4 = proxy.$utils.findIndexByField(
      fourList.value.children,
      "_id",
      type[3]
    );
    current.value.index4 = index4;
  }
}

async function getList() {
  let resp = await proxy.$apis.webCourse({ type: "query" });
  counter.setYcParams("courseList", resp);
  if (false) {
    setNewArr();
  } else {
    setDefault();
    setNewList();
  }
}

function setCurrent(type, index) {
  current.value[type] = index;
  if (type === "index1") {
    current.value.index2 = null;
    current.value.index3 = null;
    current.value.index4 = null;
  } else if (type === "index2") {
    current.value.index3 = null;
    current.value.index4 = null;
  } else if (type === "index3") {
    current.value.index4 = null;
  }
  isSelectAll.value = false;
  setNewList();
}

function setNewArr() {
  let arr = [];
  let type;
  if (
    fourList.value &&
    fourList.value.children &&
    fourList.value.children.length
  ) {
    type = fourList.value.children[current.value.index4]._id;
  } else if (
    threeList.value &&
    threeList.value.children &&
    threeList.value.children.length
  ) {
    type = threeList.value.children[current.value.index3]._id;
  } else if (
    twoList.value &&
    twoList.value.children &&
    twoList.value.children.length
  ) {
    type = twoList.value.children[current.value.index2]._id;
  } else {
    type = list.value[current.value.index1]._id;
  }
  originalCourseList.forEach((element) => {
    if (element.type.includes(type)) arr.push(element);
  });
  courseList.value = proxy.$utils.arrayUnique2(arr, "_id");
}

//设置新的数组
function setNewList() {
  let type;
  if (proxy.$utils.isNumber(current.value.index4)) {
    type = fourList.value.children[current.value.index4]._id;
  } else if (proxy.$utils.isNumber(current.value.index3)) {
    type = threeList.value.children[current.value.index3]._id;
  } else if (proxy.$utils.isNumber(current.value.index2)) {
    type = twoList.value.children[current.value.index2]._id;
  } else {
    type = list.value[current.value.index1]._id;
  }
  let arr = [];
  originalCourseList.value.forEach((element) => {
    if (element.type.includes(type)) arr.push(element);
  });
  courseList.value = proxy.$utils.arrayUnique2(arr, "_id");
}

function calculateDepth(jsonArray, field) {
  let maxDepth = 1;
  function calculate(jsonArray, currentDepth) {
    jsonArray.forEach((item) => {
      if (item[field] && Array.isArray(item[field]) && item[field].length) {
        maxDepth = Math.max(maxDepth, currentDepth + 1);
        calculate(item[field], currentDepth + 1);
      }
    });
  }
  calculate(jsonArray, 1);
  return maxDepth;
}
</script>

<style lang="scss" scoped>
.content {
  background-color: #f8f8f8;
}
.classification {
  padding: 15px;
  .cell {
    margin-bottom: 25px;
    .box {
      margin-top: 10px;
      padding-right: 20px;
      border-left: 1px solid #9a9a9b;
      padding-left: 3px;
    }
    .active {
      color: #4196a2;
      border-left: 1px solid #4196a2;
    }
    .box:hover {
      text-decoration: underline;
    }
  }
  .courses {
    margin-top: 50px;
    gap: 25px 15px; //上下间距 左右间距
    .box {
      background-color: white;
      padding-bottom: 10px;
      border-radius: 10px;
      box-shadow: 2px 5px 5px 2px #e2e2e2;
      overflow: hidden;
    }
    .info {
      padding: 5px;
      .twoPrice {
        .newPrice {
          color: #f66604;
        }
        .oldPrice {
          text-decoration: line-through;
          color: #999999;
          margin-left: 10px;
        }
      }
      .price {
        color: #f66604;
      }
      .desc {
        color: #333333;
        margin: 8px 0 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 100%;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        word-break: break-all;
      }
      .time {
        color: #686868;
      }
    }
    .btn {
      background-color: #4196a2;
      border-radius: 25px;
      text-align: center;
      color: white;
      line-height: 28px;
      cursor: pointer;
      width: calc(100% - 30px);
      margin: 15px auto 0;
    }
  }
}
</style>
